package lu.uni.adtool.ui;

import java.awt.Frame;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import javax.jnlp.FileContents;
import javax.jnlp.FileOpenService;
import javax.jnlp.ServiceManager;
import javax.jnlp.UnavailableServiceException;

import javax.swing.JLabel;

/**
 * Provides static methods for choosing file to open or save.
 * 
 * @author Piot Kordy
 */
public class JWSFileHandler extends FileHandler
{
  /**
   * Constructs a new instance.
   */
  public JWSFileHandler(Frame window)
  {
    this(null, window);
  }

  /**
   * Constructs a new instance.
   * 
   * @param status
   *          status line to which we report.
   * @param window parent window
   */
  public JWSFileHandler(final JLabel status, final Frame window)
  {
    super(status, window);
  }

  public ObjectInputStream getLoadLayoutStream()
  {
    ObjectInputStream in = null;
    FileOpenService fos = null;
    FileContents fileContents = null;
    try {
      fos = (FileOpenService) ServiceManager
          .lookup("javax.jnlp.FileOpenService");
    }
    catch (UnavailableServiceException exc) {
      report("Open command failed: " + exc.getLocalizedMessage());
    }

    if (fos != null) {
      try {
        fileContents = fos.openFileDialog(null, null);
      }
      catch (Exception exc) {
        report("Open command failed: " + exc.getLocalizedMessage());
      }
    }

    if (fileContents != null) {
      try {
        // This is where a real application would do something
        // with the file.
        report("Opened file: " + fileContents.getName() + ".");
        in = new ObjectInputStream(fileContents.getInputStream());
      }
      catch (IOException exc) {
        report("Problem opening file: " + exc.getLocalizedMessage());
      }
    }
    else {
      report("User canceled open request.");
    }
    return in;
  }
  /**
   * Update status line with text.
   * 
   * @param s new text for status line
   */
  private void report(final String s)
  {
    if (statusLine == null) {
      System.out.println(s);
    }
    else {
      statusLine.setText(s);
    }
  }

}

